package com.holike.crm.fragment.bank;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gallopmark.recycler.adapterhelper.CommonAdapter;
import com.holike.crm.R;
import com.holike.crm.base.MyFragment;
import com.holike.crm.bean.BillListBean;
import com.holike.crm.bean.MultiItem;
import com.holike.crm.dialog.CalendarPickerDialog;
import com.holike.crm.helper.RefreshAndLoadMoreHelper;
import com.holike.crm.presenter.fragment.BillPresenter;
import com.holike.crm.util.CopyUtil;
import com.holike.crm.util.ParseUtils;
import com.holike.crm.util.TimeUtil;
import com.holike.crm.view.fragment.BillView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;

import java.util.Date;
import java.util.List;


/**
 * 账单明细列表
 */
public class BillDetailListFragment extends MyFragment<BillPresenter, BillView> implements BillView, RefreshAndLoadMoreHelper.Callback {
    private String mStartTime, mEndTime;
    private List<Date> mSelectedDates;
    private LinearLayout mTimeLayout;
    private TextView mDatetimeTextView;
    private TextView mThisMonthTextView;

    private RefreshAndLoadMoreHelper mHelper;

    @Override
    protected BillPresenter attachPresenter() {
        return new BillPresenter();
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_billdetail_list;
    }

    @Override
    protected void init() {
        setTitle(getString(R.string.bill_list_detail));
        mTimeLayout = mContentView.findViewById(R.id.ll_time_layout);
        mDatetimeTextView = mContentView.findViewById(R.id.tv_select_date);
        mThisMonthTextView = mContentView.findViewById(R.id.tv_this_month);
        mDatetimeTextView.setOnClickListener(view -> onSelectDate());
        mThisMonthTextView.setOnClickListener(view -> loadThisMonth());
        SmartRefreshLayout refreshLayout = mContentView.findViewById(R.id.refresh_layout);
        RecyclerView recyclerView = mContentView.findViewById(R.id.rv_bill_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mHelper = new RefreshAndLoadMoreHelper(refreshLayout, 1, 20, this);
        BillListAdapter adapter = new BillListAdapter(mContext, mHelper.getListBeans());
        recyclerView.setAdapter(adapter);
        mHelper.setAdapter(adapter);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mStartTime = bundle.getString("startTime");
            mEndTime = bundle.getString("endTime");
        }
        if (!TextUtils.isEmpty(mStartTime) || !TextUtils.isEmpty(mEndTime)) {
            mThisMonthTextView.setVisibility(View.VISIBLE);
        } else {
            mThisMonthTextView.setVisibility(View.INVISIBLE);
        }
        initData();
    }

    private void onSelectDate() {
        new CalendarPickerDialog.Builder(mContext).maxDate(new Date()).withSelectedDates(mSelectedDates)
                .clickToClear(true)
                .calendarRangeSelectedListener(new CalendarPickerDialog.OnCalendarRangeSelectedListener() {
                    @Override
                    public void onLeftClicked(CalendarPickerDialog dialog) {

                    }

                    @Override
                    public void onRightClick(CalendarPickerDialog dialog, List<Date> selectedDates, Date start, Date end) {
                        dialog.dismiss();
                        mSelectedDates = selectedDates;
                        if (!selectedDates.isEmpty()) {
                            mStartTime = TimeUtil.dateToStamp(start, false);
                            mEndTime = TimeUtil.dateToStamp(end, true);
                            String text = TimeUtil.timeMillsFormat(mStartTime) + "-" + TimeUtil.timeMillsFormat(mEndTime);
                            mDatetimeTextView.setText(text);
                            mThisMonthTextView.setVisibility(View.VISIBLE);
                        } else {
                            mStartTime = null;
                            mEndTime = null;
                        }
                        initData();
                    }
                }).show();
    }

    private void loadThisMonth() {
        mThisMonthTextView.setVisibility(View.INVISIBLE);
        mStartTime = null;
        mEndTime = null;
        initData();
    }

    private void initData() {
        showLoading();
        mHelper.initData();
    }

    @Override
    public void onSuccess(BillListBean bean) {
        dismissLoading();
        if (mTimeLayout.getVisibility() != View.VISIBLE) {
            mTimeLayout.setVisibility(View.VISIBLE);
        }
        Date startDate = TimeUtil.stampToDate(bean.getStartTime());
        Date endDate = TimeUtil.stampToDate(bean.getEndTime());
        String text = TimeUtil.timeMillsFormat(startDate) + "-" + TimeUtil.timeMillsFormat(endDate);
//        String text = TimeUtil.stampToString(bean.getStartTime() + 1, "yyyy.MM.dd") + "-" + TimeUtil.stampToString(bean.getEndTime() + 1, "yyyy.MM.dd");
        mDatetimeTextView.setText(text);
        mHelper.setResult(bean.getPageData());
    }

    @Override
    public void onFailure(String failReason) {
        dismissLoading();
        mHelper.onFailure(failReason);
    }

    @Override
    protected void reload() {
        initData();
    }

    @Override
    public void onLoadData(int pageNo, int pageSize) {
        mPresenter.getHeadData(pageNo, pageSize, mStartTime, mEndTime);
    }

    @Override
    public void onNoResult() {
        noResult();
    }

    @Override
    public void onHasData() {
        hasData();
    }

    @Override
    public void onLoadDataFailure(String failReason, boolean hide) {
        if (hide) {
            noNetwork(failReason);
        } else {
            showShortToast(failReason);
        }
    }

    private class BillListAdapter extends CommonAdapter<MultiItem> {

        BillListAdapter(Context context, List<MultiItem> mDatas) {
            super(context, mDatas);
        }

        @Override
        public void onBindHolder(RecyclerHolder holder, MultiItem multiItem, int position) {
            if (holder.getItemViewType() == 2) {
                holder.setText(R.id.mNoMoreTextView, mContext.getString(R.string.list_no_more));
            } else {
                final BillListBean.PageDataBean pageDataBean = (BillListBean.PageDataBean) multiItem;
                holder.setText(R.id.tv_cztxt, MyFragment.textEmpty(pageDataBean.getCztxt()));
                holder.setText(R.id.tv_order_bstkd, MyFragment.textEmpty(pageDataBean.getBstkd()));
                holder.setText(R.id.tv_order_date, MyFragment.textEmpty(pageDataBean.getZdate()));
                holder.setText(R.id.tv_money, ParseUtils.parseDouble(pageDataBean.getMoney()) > 0 ? "+" + MyFragment.textEmptyNumber(pageDataBean.getMoney()) : MyFragment.textEmptyNumber(pageDataBean.getMoney()));
                holder.setTextColor(R.id.tv_money, ParseUtils.parseDouble(pageDataBean.getMoney()) > 0 ? mContext.getResources().getColor(R.color.bg_homepage_new) : mContext.getResources().getColor(R.color.textColor4));
                holder.setVisibility(R.id.v_line, getItemCount() != position + 1);
                holder.itemView.setOnClickListener(view -> BillDetailFragment.start(BillDetailListFragment.this, pageDataBean));
                holder.itemView.setOnLongClickListener(view -> {
                    String orderId = pageDataBean.getOrderId();
                    if (TextUtils.isEmpty(orderId)) return true;
                    CopyUtil.copy(mContext, orderId);
                    showShortToast("订单号已复制到粘贴板");
                    return false;
                });
            }
        }

        @Override
        public int getItemViewType(int position) {
            return mDatas.get(position).getItemType();
        }

        @Override
        protected int bindView(int viewType) {
            if (viewType == 2) {
                return R.layout.item_nomore_data;
            }
            return R.layout.item_bill_list_detail;
        }
    }
}
